<template>
  <el-container>
    <el-header>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="search.usersName" placeholder="用户名称" />
        </el-col>
        <el-col :span="6">
          <el-input v-model="search.email" placeholder="邮箱地址" />
        </el-col>
        <el-col :span="6">
          <el-select v-model="search.is_active" placeholder="用户状态">
            <el-option label="所有" value="" />
            <el-option label="启用" value="true" />
            <el-option label="禁用" value="false" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-col>
      </el-row>
    </el-header>
    <el-main>
      <el-row style="margin-bottom: 20px">
        <el-button type="primary" @click="handleAdd">+ 新增</el-button>
        <el-button @click="handleAllEdit">
          <img src="../assets/update.png" alt="" style="width: 20px; height: 20px; margin-right: 5px" />
          修改
        </el-button>
        <el-button @click="handleImport">导入</el-button>
        <el-button @click="handleExport">导出</el-button>
      </el-row>

      <el-table :data="paginatedUserData" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="user_id" label="用户ID" />
        <el-table-column prop="username" label="用户名称" />
        <el-table-column prop="email" label="邮箱地址" />
        <el-table-column prop="role" label="角色">
          <template #default="{ row }">
            <span @click="handleRoleClick(row)">{{ row.role }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="is_active" label="用户状态">
          <template #default="{ row }">
            <el-switch
              v-model="row.is_active"
              class="ml-2"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间">
          <template #default="{ row }">
            {{ dayjs(row.created_at).format("YYYY-MM-DD") }}
          </template>
        </el-table-column>
        <el-table-column prop="updated_at" label="修改时间">
          <template #default="{ row }">
            {{ dayjs(row.updated_at).format("YYYY-MM-DD") }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="text" @click="handleEdit(scope.row)">重置密码</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog v-model="dialogVisible" title="编辑角色" width="500px" :append-to-body="false" class="role-dialog">
        <el-form :model="formData" label-width="100px" class="role-form">
          <el-form-item label="用户名称">
            <el-input v-model="formData.name" disabled class="role-input" />
          </el-form-item>
          <el-form-item label="角色">
            <el-select v-model="formData.role" placeholder="请选择角色" class="role-select">
              <el-option v-for="item in roles" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false" class="cancel-btn">取消</el-button>
            <el-button type="primary" @click="handleConfirm" class="confirm-btn">确认</el-button>
          </span>
        </template>
      </el-dialog>
      <el-pagination
        background
        layout="sizes, prev, pager, next"
        :total="filteredData.length"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :current-page="currentPage"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        class="pagination-container"
      />
    </el-main>
  </el-container>
</template>

<script lang="ts" setup>
  import { onMounted, ref, computed } from "vue";
  import api from "../axios/api";
  import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
  // @ts-ignore
  import dayjs from "dayjs";

  const search = ref({
    usersName: "",
    email: "",
    is_active: ""
  });

  const userData = ref([]);
  const username = localStorage.getItem("studentId");
  const token = localStorage.getItem("token");

  const currentPage = ref(1);
  const pageSize = ref(10);

  // 存储选中的行
  const selectedRows = ref([]);
  const handleSelectionChange = (selection: any) => {
    selectedRows.value = selection;
  };
  const dialogVisible: any = ref(false);
  const formData = ref({
    name: "",
    role: ""
  });
  const roles = ref([
    { value: "admin", label: "管理员" },
    { value: "organizer", label: "组织者" },
    { value: "student", label: "学生" }
  ]);
  const handleRoleClick = (row: any) => {
    dialogVisible.value = true;
    console.log(row);
    console.log(dialogVisible.value);
    formData.value.name = row.username;
    formData.value.role = row.role;
  };
  const handleConfirm = () => {
    // console.log(formData.value)
    api
      .updateUserRole(username, token, formData.value.name, formData.value.role)
      .then(res => {
        ElMessage.success("修改成功");
        dialogVisible.value = false;
        handleUserData();
      })
      .catch(err => {
        ElMessage.error("修改失败", err);
      });
  };
  // 计算当前页的数据
  const paginatedUserData = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return filteredData.value.slice(start, end);
  });

  // 获取用户数据
  const handleUserData = async () => {
    const loading = ElLoading.service({
      lock: true,
      text: "处理中...",
      background: "rgba(0, 0, 0, 0.7)"
    });
    try {
      const response = await api.getUserInfo(username, token);
      console.log("获取用户数据成功:", response.data);
      userData.value = response.data;
      filteredData.value = response.data;
      ElMessage.success("获取用户数据成功");
    } catch (error) {
      console.error("获取用户数据错误:", error);
    } finally {
      loading.close();
    }
  };

  // 搜索功能
  const filteredData = ref([]);

  const handleSearch = () => {
    filteredData.value = userData.value.filter((item: any) => {
      const usersNameMatch = item.username.includes(search.value.usersName) || search.value.usersName === "";
      const emailMatch = item.email.includes(search.value.email) || search.value.email === "";
      const statusMatch = search.value.is_active === "" || item.is_active === (search.value.is_active === "true");
      return usersNameMatch && emailMatch && statusMatch;
    });
    currentPage.value = 1;
    ElMessage.success("查询成功");
  };

  // 重置搜索条件
  const handleReset = () => {
    search.value = { usersName: "", email: "", is_active: "" };
    filteredData.value = userData.value;
    currentPage.value = 1;
    ElMessage.success("重置成功");
  };

  // 新增逻辑
  const handleAdd = () => {
    // 实现新增逻辑
  };

  // 重置密码逻辑
  const adminUsername = localStorage.getItem("studentId");
  const adminToken = localStorage.getItem("token");
  const newPassword = "123"; // 默认新密码
  const handleEdit = (row: any) => {
    const username = row.username;
    ElMessageBox.confirm("确定要重置密码吗？", "重置密码", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
      .then(() => {
        api
          .forceUser(username, newPassword, adminUsername, adminToken)
          .then(res => {
            ElMessage.success(`重置密码成功，新密码为: ${newPassword}`);
          })
          .catch(err => {
            ElMessage.error("重置密码失败");
            console.error("重置密码失败:", err);
          });
      })
      .catch(() => {
        ElMessage.info("取消重置密码");
      });
  };

  const handleAllEdit = () => {
    if (selectedRows.value.length === 0) {
      ElMessage.warning("请选择要重置密码的用户");
      return;
    }
    const usernames: string = selectedRows.value.map((item: any) => item.username).join(", ");
    ElMessageBox.confirm("确定要重置密码吗？", "重置密码", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
      .then(() => {
        // 调用后端 API 重置密码
        api
          .forceUser(usernames, newPassword, adminUsername, adminToken)
          .then(res => {
            ElMessage.success(`重置密码成功，新密码为: ${newPassword}`);
          })
          .catch(err => {
            ElMessage.error("重置密码失败");
            console.error("重置密码失败:", err);
          });
      })
      .catch(() => {
        ElMessage.info("取消重置密码");
      });
  };
  // 导入逻辑
  const handleImport = () => {
    // 实现导入逻辑
  };

  // 导出逻辑
  const handleExport = () => {
    // 实现导出逻辑
  };

  // 切换用户状态
  const handleStatusChange = (row: any) => {
    if (adminUsername === row.username && row.role === "admin") {
      ElMessage.warning("不能修改自己的状态！");
      return;
    }

    ElMessageBox.confirm(`确定要切换${row.username}的用户状态吗？`, "切换用户状态", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
      .then(() => {
        // 用户确认后，调用 API 更新状态
        api
          .userStatus(adminUsername, token, row.username, row.is_active)
          .then(res => {
            ElMessage.success(`${row.username}用户状态更新成功`);
          })
          .catch(err => {
            ElMessage.error("用户状态更新失败");
            //重新加载数据
          });
      })
      .catch(() => {
        ElMessage.info("取消切换用户状态");
      });
  };

  // 处理页码变化
  const handlePageChange = (page: number) => {
    currentPage.value = page;
  };

  // 处理每页条数变化
  const handleSizeChange = (size: number) => {
    pageSize.value = size;
    currentPage.value = 1;
  };

  onMounted(() => {
    handleUserData();
  });
</script>

<style lang="less" scoped>
  .el-header {
    padding: 20px;
    margin: auto;
  }

  .el-main {
    padding: 20px;
  }
  .pagination-container {
    margin-top: 20px;
    text-align: center;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-wrap: wrap;
  }
  .role-dialog {
    .el-dialog__header {
      border-bottom: 1px solid #e8e8e8;
      padding: 16px 20px;
      margin: 0;

      .el-dialog__title {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
      }
    }

    .el-dialog__body {
      padding: 20px;
    }

    .el-dialog__footer {
      border-top: 1px solid #e8e8e8;
      padding: 16px 20px;
      text-align: right;
    }
  }

  .role-form {
    .el-form-item {
      margin-bottom: 20px;

      &:last-child {
        margin-bottom: 0;
      }
    }

    .role-input,
    .role-select {
      width: 100%;
    }
  }

  .dialog-footer {
    .cancel-btn {
      margin-right: 10px;
      background-color: #f5f7fa;
      border-color: #dcdfe6;
      color: #606266;

      &:hover {
        background-color: #e4e7ed;
        border-color: #c0c4cc;
      }
    }

    .confirm-btn {
      background-color: #409eff;
      border-color: #409eff;
      color: #fff;

      &:hover {
        background-color: #66b1ff;
        border-color: #66b1ff;
      }
    }
  }
</style>
